package com.sergio.accounting.service.impl;

import com.sergio.accounting.dto.FileUploadResponse;
import com.sergio.accounting.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    private static final String UPLOAD_DIR = "upload";
    private static final String AVATAR_DIR = "avatars";
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
    private static final String[] ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif"};
    private static final String OTHER_DIR = "other";

    @Override
    public FileUploadResponse uploadAvatar(MultipartFile file, Long userId) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return FileUploadResponse.builder()
                        .success(false)
                        .message("文件不能为空")
                        .build();
            }

            if (file.getSize() > MAX_FILE_SIZE) {
                return FileUploadResponse.builder()
                        .success(false)
                        .message("文件大小不能超过5MB")
                        .build();
            }

            // 验证文件扩展名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !isValidImageExtension(originalFilename)) {
                return FileUploadResponse.builder()
                        .success(false)
                        .message("只支持jpg、jpeg、png、gif格式的图片")
                        .build();
            }

            // 创建上传目录
            String avatarDir = UPLOAD_DIR + File.separator + AVATAR_DIR;
            Path uploadPath = Paths.get(avatarDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成唯一文件名
            String fileExtension = getFileExtension(originalFilename);
            String fileName = "avatar_" + userId + "_" + UUID.randomUUID().toString() + fileExtension;
            Path filePath = uploadPath.resolve(fileName);

            // 保存文件
            Files.copy(file.getInputStream(), filePath);

            // 构建文件URL
            String fileUrl = "/upload/" + AVATAR_DIR + "/" + fileName;

            log.info("头像上传成功: userId={}, fileName={}, fileUrl={}", userId, fileName, fileUrl);

            return FileUploadResponse.builder()
                    .success(true)
                    .fileName(fileName)
                    .fileUrl(fileUrl)
                    .message("头像上传成功")
                    .build();

        } catch (IOException e) {
            log.error("头像上传失败: userId={}, error={}", userId, e.getMessage(), e);
            return FileUploadResponse.builder()
                    .success(false)
                    .message("头像上传失败: " + e.getMessage())
                    .build();
        }
    }

    @Override
    public FileUploadResponse uploadOtherFile(MultipartFile file) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return FileUploadResponse.builder()
                        .success(false)
                        .message("文件不能为空")
                        .build();
            }

            if (file.getSize() > MAX_FILE_SIZE) {
                return FileUploadResponse.builder()
                        .success(false)
                        .message("文件大小不能超过5MB")
                        .build();
            }

            // 验证文件扩展名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !isValidImageExtension(originalFilename)) {
                return FileUploadResponse.builder()
                        .success(false)
                        .message("只支持jpg、jpeg、png、gif格式的图片")
                        .build();
            }

            // 创建上传目录
            String otherDir = UPLOAD_DIR + File.separator + OTHER_DIR;
            Path uploadPath = Paths.get(otherDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成唯一文件名
            String fileExtension = getFileExtension(originalFilename);
            String fileName = "other_" + UUID.randomUUID().toString() + fileExtension;
            Path filePath = uploadPath.resolve(fileName);

            // 保存文件
            Files.copy(file.getInputStream(), filePath);

            // 构建文件URL
            String fileUrl = "/upload/" + OTHER_DIR + "/" + fileName;

            log.info("其他文件上传成功: fileName={}, fileUrl={}", fileName, fileUrl);

            return FileUploadResponse.builder()
                    .success(true)
                    .fileName(fileName)
                    .fileUrl(fileUrl)
                    .message("文件上传成功")
                    .build();

        } catch (IOException e) {
            log.error("其他文件上传失败: error={}", e.getMessage(), e);
            return FileUploadResponse.builder()
                    .success(false)
                    .message("文件上传失败: " + e.getMessage())
                    .build();
        }
    }

    @Override
    public boolean deleteAvatar(String fileName) {
        try {
            if (fileName == null || fileName.isEmpty()) {
                return false;
            }

            Path filePath = Paths.get(UPLOAD_DIR, AVATAR_DIR, fileName);
            if (Files.exists(filePath)) {
                Files.delete(filePath);
                log.info("头像文件删除成功: {}", fileName);
                return true;
            }
            return false;
        } catch (IOException e) {
            log.error("头像文件删除失败: fileName={}, error={}", fileName, e.getMessage(), e);
            return false;
        }
    }

    private boolean isValidImageExtension(String filename) {
        String extension = getFileExtension(filename).toLowerCase();
        for (String allowedExt : ALLOWED_EXTENSIONS) {
            if (allowedExt.equals(extension)) {
                return true;
            }
        }
        return false;
    }

    private String getFileExtension(String filename) {
        int lastDotIndex = filename.lastIndexOf('.');
        return lastDotIndex > 0 ? filename.substring(lastDotIndex) : "";
    }
}
